<?php
/**
 * Model
 */
class Private_Messages extends Psa_Model {
		
	
	/**
	 * Checks if arguments are integers and sums them
	 * $limit=0 znaci da nema limita
	 */
	function restore_all($limit=0){
		
		$sql = "SELECT * FROM private_messages WHERE author_id = {$this->psa_registry->user->id}";
		
		if($limit)
			$sql.="LIMIT $limit";
		
		$this->psa_database->query($sql);
		return $this->psa_database->fetch_all();
	}
	
	function count_unread(){
	
		$sql1 = "SELECT COUNT(is_read) as unread FROM private_messages WHERE author_id = {$this->psa_registry->user->id} AND is_read = 0 AND message = 1 GROUP BY author_id";
		$this->psa_database->query($sql1);
		$return['message'] = $this->psa_database->fetch_row();
		if(!(isset($return['message']) && $return['message']))
			$return['message']['unread'] = 0;
		
		$sql2 = "SELECT COUNT(is_read) as unread FROM private_messages WHERE author_id = {$this->psa_registry->user->id} AND is_read = 0 AND to_do = 1 GROUP BY author_id";
		$this->psa_database->query($sql2);
		$return['to_do'] = $this->psa_database->fetch_row();
		if(!(isset($return['to_do']) && $return['to_do']))
			$return['to_do']['unread'] = 0;
		
		$sql3 = "SELECT COUNT(is_read) as unread FROM private_messages WHERE author_id = {$this->psa_registry->user->id} AND is_read = 0 AND task = 1 GROUP BY author_id";
		$this->psa_database->query($sql3);
		$return['task'] = $this->psa_database->fetch_row();
		if(!(isset($return['task']) && $return['task']))
			$return['task']['unread'] = 0;
		
		$sql3 = "SELECT COUNT(is_read) as unread FROM private_messages WHERE author_id = {$this->psa_registry->user->id} AND is_read = 0 AND is_important = 1 GROUP BY author_id";
		$this->psa_database->query($sql3);
		$return['important'] = $this->psa_database->fetch_row();
		if(!(isset($return['important']) && $return['important']))
			$return['important']['unread'] = 0;
		
		$return['sum']['unread']=$return['message']['unread'] + $return['to_do']['unread'] + $return['task']['unread'] + $return['important']['unread'];
		
		return json_encode($return);
	}
	
	function count_online_user(){
		
		$sql2 = "SELECT COUNT(*) AS online_user_all FROM psa_user WHERE last_activity > (NOW() - INTERVAL {$this->psa_registry->CFG['header']['online_user_last_activity']} MINUTE)";
		$this->psa_database->query($sql2);
		$return['count'] = $this->psa_database->fetch_row();
		
		if(isset($return['count']) && $return['count']){
			$sql1 = "SELECT id, username, full_name, last_activity FROM psa_user WHERE last_activity > (NOW() - INTERVAL {$this->psa_registry->CFG['header']['online_user_last_activity']} MINUTE) ORDER BY last_activity DESC LIMIT {$this->psa_registry->CFG['header']['online_user_limit']}";
			$this->psa_database->query($sql1);
			$return['online_user'] = $this->psa_database->fetch_all();
		} else 
			$return['online_user'] = 0; 
		
		return json_encode($return);
	}
	
	
	

}
